//
//  NSObject+LNExtension.m
//  NetEaseNewsDemo
//
//  Created by Lining on 15/5/11.
//  Copyright (c) 2015年 Lining. All rights reserved.
//

#import "NSObject+LNExtension.h"
#import <objc/runtime.h>

@implementation NSObject (LNExtension)

/** 字典转模型 */
+ (instancetype)objectWithDict:(NSDictionary *)dict {
    
    id obj = [[self alloc] init];
    NSArray *properties = [self properties];
    [properties enumerateObjectsUsingBlock:^(NSString *propertyName, NSUInteger idx, BOOL *stop) {
       
        if (dict[propertyName] != nil) {
            [obj setValue:dict[propertyName] forKey:propertyName];
        }
    }];
    
    return obj;
}

const char * propertiesKey = "propertiesKey";

/** 动态获取某个的属性列表 */
+ (NSArray *)properties {
    
    // 为了提高性能 从关联对象中取
    NSArray *array = objc_getAssociatedObject(self, propertiesKey);
    if (array != nil) {
        return array;
    }
    
    unsigned int outCount;
    objc_property_t *list = class_copyPropertyList([self class], &outCount);
    NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:outCount];
    for (int i = 0; i < outCount; i++) {
        
        const char *propertyName = property_getName(list[i]);
        [tmpArray addObject:[NSString stringWithUTF8String:propertyName]];
    }
    // 设置关联对象
    objc_setAssociatedObject(self, propertiesKey, tmpArray, OBJC_ASSOCIATION_COPY_NONATOMIC);
    return tmpArray.copy;
}

@end
